// require('babel-polyfill');
$(function(){
	FastClick.attach(document.body);
	
});

var userInfor = {
		userCode : getQueryString('userCode') || '',
		sessionId : getQueryString('sessionId') || '',
		mobile : getQueryString('mobile') || '',
		//source : getQueryString('source') || ''
		//channelId : getQueryString('channelId') || ''
}
//alert(userInfor.userCode+"--"+.sessionId);
//alert(userInfor.userId+":"+userInfor.sessionId);
var lotteryTool = {
	promotioId : 0,
	//01加息券 02红包 03体验金 04黄金加息券 05返现 06积分
	prizes : ["01","04","04","01","02","04","04","07","05","03","06"],
	prizeNames : ["加息券","黄金加息券","黄金加息券","加息券","红包","黄金加息券","黄金加息券","未中奖","返现","体验金","积分"],
	isPrize : false,
	target : 1,
	edmond : 1,
	edmonds : {"02":1,"03":2,"01":3,"04":4,"05":5},
	lottery : $("#lottery"),
	notWinning : $("#notWinning"),
	winning : $("#Winning"),
	couponArr : [],
	getEdmond : function(prize){
		for(var i in this.edmonds){
			if(prize == i){
				return this.edmonds[i];
			}
		}
	},
	getLocation : function(awardtype){

		for(var i=0; i<this.prizes.length; i++){
			if(awardtype == this.prizes[i]){
				return i;
			}
		}
      
	},
	getPrize : function(awardtype){
		return this.prizes[awardtype];
	},
	getPrizeName : function(awardtype){
		return this.prizeNames[this.getLocation(awardtype)];
	},
	getUnit : function(type){
		//体验金、加息劵、返现、黄金加息劵
		switch(type){
			case '01':
			case '04':
				return '%';
				break;
			default:
				return '元';
				break
		}
	},
	formatDate : function(nS){
		var now = new Date(nS);
		var   year=now.getFullYear();     
	  	var   month=now.getMonth()+1;     
	  	var   date=now.getDate();     
	  	var   hour=now.getHours();     
	  	var   minute=now.getMinutes();     
	  	var   second=now.getSeconds(); 
		if(month < 10){
			month = "0"+month;
		} 
		if(date < 10){
			date = "0"+date;
		} 
		if(hour < 10){
			hour = "0"+hour;
		} 
		if(minute < 10){
			minute = "0"+minute;
		} 
		if(second < 10){
			second = "0"+second;
		}  
	  return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;
	},
	parseNum : function(num){
		if(/\.0[1-9]/.test(num)){
			return num;
		}
		if(/\.00/.test(num)){
			return parseInt(num);
		}
		if(/\.\d0/.test(num)){
			return parseFloat(num).toFixed(1);
		}
		return num;
	},
	ajax : XZQB.ajax,
	turn : function(type){
		switch(type){
			case 'home' :
					uti.turnHome();
				break;
			case 'loans' :
					uti.turnAliveBao();
				break;
			case 'coupon' : 
					uti.turnCoupon(this.edmond);
				break;
			case 'login' : 
					uti.login();
		}
	}
}
function autoScroll(obj){
	var ul = $(obj).find("ul");
	if($(obj).height() < ul.height()){
		$(obj).find("ul").animate({
			marginTop : -(ul.find("li").height())
		},1000,function(){
			$(this).css({marginTop : "0px"}).find("li:first").appendTo(this);
		})
	}
}
$(function () {
	'use strict'
  //记录是否阻止滚动
  var disableScroll = false;
  //如果弹出对话框时，底层的视图就不让滚动了
  document.addEventListener('touchmove', function(e) {
    if(disableScroll){
        e.preventDefault();
    }
   }, false);
	var $mask = $(".mask"),
		$btnCls = $(".ico-close"),
		$btnKnow = $(".ico-know");
	function btnClick(){
    // disableScroll = true;
		var target = $(this).data("target");
		$(document.body).css({height:$(window).height(),overflow:'hidden'});
		$("#"+target).show();
		$mask.show();
	}
	$(".a-rule").on("click",btnClick);
	$('.des_btn').on("click",function(){
		$('#recorDes').show();
	});
	$(".mask").click(function(){
		// var isRecorDes=$("#recorDes").css('display') 
		// var isMyRecord=$("#myRecord").css('display')
		// console.log(isRecorDes+isMyRecord)
		// if(isRecorDes =='block' ||isMyRecord =='block'){
  //           $(this).hide();
		//     $("#recorDes").hide();
		//     $("#myRecord").hide();
		//     $(document.body).css({height:'auto',overflow:'visible'});
		// }
		
	})
	$('.des_btn').on('click',btnClick);
	$btnCls.click(function(){
		var target = $(this).data("target");
		if(target){
			lotteryTool.lottery.hide();
			if(target == "notWinning"){
				lotteryTool.notWinning.show();
			}else{
				lotteryTool.winning.show();
			}
		}
		$(this).parent().parent().hide();
		$mask.hide();
		$(document.body).css({height:'auto',overflow:'visible'});
	});
	$btnKnow.click(function(){
    // disableScroll = false;
		$(this).parent().parent().hide();
		$mask.hide();
		$(document.body).css({height:'auto',overflow:'visible'});
	});
	function Login2(){
		$(".spinner").hide();
		lotteryTool.lottery.show();
		$(".td_5 a").off().click(function(){
			lotteryTool.turn("login");
		});
		$(".kindList").hide();
		$("#awardRecords").empty().append("<li style='text-align:center' class='noLogin'>请登录查看</li>");
		$(".a-record").off().on("click",function(){
			lotteryTool.turn("login");
			// if(supporter.os.ios){
			// 	$mask.show();
			// 	$(".error").show();
			// }else{
			// 	lotteryTool.turn("home");
			// }
		});
	}
	function Login(){
		$(".spinner").hide();
		lotteryTool.lottery.show();
		$(".td_5 a").off().click(function(){
			lotteryTool.turn("login");
		});
		$(".kindList").hide();
		$("#awardRecords").empty().append("<li style='text-align: center' class='noLogin'>请登录查看</li>");
		$(".a-record").off().on("click",function(){
			lotteryTool.turn("login");
		});
	}
	if(userInfor.userCode == '' || userInfor.sessionId == ''){
		Login();
		$(".btnInvite").hide();
		return;
	}
	$(".btnInvite").show().click(function(){
	  	uti.shareActivity("https://www.xiaoziqianbao.com/pcstatic/commForm1.html?invitationNo="+ userInfor.mobile + "&mobile="+ userInfor.mobile,"我正在使用小资钱包【银行资金存管平台】","现在注册送388元红包+首投送10元现金！等你加入>>","https://www.xiaoziqianbao.com/pcstatic/ic_29pt@2x-1.png");
	});

//抽奖相关
//获取活动编号
const getPromotNo = function(){
	return new Promise((resolve,reject) =>{
           lotteryTool.ajax({
           	  param:{
           	  	"sessionId": userInfor.sessionId,   //$("#ssid").val()
           	  	"userCode": userInfor.userCode     //$("#uid").val()
           	  },
           	  port : 'C_APP_4113',        //获取活动ID
           	  success:function(data){
           	  	 let result = data ;
           	  	 
           	  	 if(result.returnCode ="000000"){
           	  	 	//lotteryTool.promotNo = result.promotNo;
           	  	 	if(result.promotDraw){
           	  	 		resolve(result.promotDraw.promotNo)
           	  	 	}else{
           	  	 		resolve("该活动已经停止")
           	  	 	}
           	  	 	
           	  	 }else{
           	  	 	Login2()
           	  	 }
                 
           	  },
           	  error:function(data){
           	  	reject(data.message)
           	  }
           })
	  }
	)
}

//所有抽奖记录查询  拿不到活动编号是不能进行查询的
const allLotteryRecords = function(promotNo){
    return new Promise((resolve,reject)=>{
    	 lotteryTool.ajax({
						param : {
							"promotNo": promotNo,
							"userCode": userInfor.userCode,//$("#uid").val()
							"sessionId": userInfor.sessionId//$("#ssid").val()
						},
						port : 'C_H5_3023', //中奖纪录
						success : function(data){
							let result = data ;
							console.log(result)
							let $awardRecords = $("#awardRecords");
								//$falseAwardRecords = $("#falseAwardRecords"),
							if (result.returnCode == "000000") {
								// resolve(data)  是否具有假数据需要确认
							    if(result.userRecord.length == 0){
									$awardRecords.empty().append("<li style='text-align: center;'>暂无中奖纪录</li>");
								}else{
									let html = '',
										cls = "even";
									// for(var i=0,l=result.falseAwardRecords.length; i<l;i++){
									// 	if(i%2){
									// 		cls = "even"      //偶数所加的类名
									// 	}else{
									// 		cls = "old"       //奇数类名
									// 	}
									// 	html += '<li class="'+cls+'"><span>恭喜'+result.falseAwardRecords[i].phone+'</span><span>抽中</span><span class="red">'+result.falseAwardRecords[i].awardname+'</span></li>';
									// }
									for(let i=0,l=result.userRecord.length; i<l;i++){
										if(i%2){
											cls = "even"      //偶数所加的类名
										}else{
											cls = "old"       //奇数类名
										}
										html += `<li  class="${cls}"><span class="span1">恭喜${result.userRecord[i].phone}</span><span class="span2">抽中</span><span class="span3 red">${lotteryTool.parseNum(result.userRecord[i].couponValue)}${lotteryTool.getUnit(result.userRecord[i].couponType)} ${lotteryTool.getPrizeName(result.userRecord[i].couponType)}</span></li>`;
									}
									$awardRecords.empty().append(html);
									setInterval(function(){autoScroll(".kindLists")},2000);
								}
																
							}else{
								Login();
							}							
							
						},
						error : function(err){
							console.log(err)
				    }
			});

       })
    }

    //用户抽奖记录查询  拿不到活动编号是不能进行查询的
	const adminLotteryRecords = function (promotNo){
		return new Promise((resolve,reject)=>{
			lotteryTool.ajax({
					param : {
							"promotNo": promotNo,
							"userCode": userInfor.userCode,//$("#uid").val()
							"sessionId": userInfor.sessionId//$("#ssid").val()
						},
						port : 'C_H5_3022', //用户中奖纪录
						success : function(data){
							let result = data;
							let $personAwardRecords = $("#personAwardRecords");
							if(result.returnCode == "000000"){
								if(result.userRecord.length == 0){
									$personAwardRecords.empty().append('<li class="noRecord"><img src="images/complianceOn-imgs/noRecord.png"></li>');
								}else{
									var cont = `<div class="bd"><ul class="rtit">
												<li><span>时间</span><span>奖品</span></li></ul><ul class="rcont">`;
									for(let i=0; i< result.userRecord.length;i++){
										 cont += `<li><span>${lotteryTool.formatDate(result.userRecord[i].createTime)}</span><span>${lotteryTool.getPrizeName(result.userRecord[i].couponType)} ${lotteryTool.parseNum(result.userRecord[i].couponValue)}${lotteryTool.getUnit(result.userRecord[i].couponType)}</span></li>`;
									}
									cont += `</ul></div>`;
									$personAwardRecords.empty().append(cont);
								}
								if(userInfor.userCode == ''){
									$(".a-record").on("click",function(){
										lotteryTool.turn("login");
										return;
									});
								}else{
								$(".a-record").on("click",btnClick);
							  }
							}else{
								Login2();
							}
						},
						error : function(err){	
							Login2() ;
							resolve() ;
					}
			});
		})
	}
	//  查询能否抽奖
const hasRightDraw = function(promotNo){
   return new Promise((resolve,reject) => {
   	   lotteryTool.ajax({
					param : {
						"promotNo": promotNo,
						"userCode": userInfor.userCode, //$("#uid").val()
						"sessionId": userInfor.sessionId//$("#ssid").val()
					},
					port : 'C_H5_3021',  //查询能否抽奖
					success : function(data){						
						let result = data;			
						if(result.returnCode == "000000"){
                            if(result.flag == 0){  // 能抽奖
                            	
                            	resolve(result.flag)
                            }else{  //已经抽过奖
                            	$(".spinner").hide();
								lotteryTool.lottery.hide();
								var awardRecord = result.drawUserRecord;
								if(awardRecord.couponType == "07"){
									lotteryTool.notWinning.show();
								}else{
									let html = fill(result.drawUserRecord,true);
									lotteryTool.winning.append(html).show();	
								}
								 reject()
                            }
				            
						}else{
						    Login2();	
						}
						
					},
					error : function(err){
						alert('你还没有登录')
						Login2();
					}
		    });
       })
    }
    //  抽奖
	function clickDraw(promotNo){
		return new Promise((resolve,reject)=>{    
	       $(".spinner").hide();
			lotteryTool.lottery.show();
			lottery.lottery({
				selector:    '#lottery',
				width:        3,
				height:       3,
				index:        -1,    // 初始位置
				initSpeed:    100,  // 初始转动速度
				aim : function(){
					var self = this;
					lotteryTool.ajax({
						param : {
							"promotNo":promotNo,
							"userCode": userInfor.userCode,//$("#uid").val()
							"sessionId": userInfor.sessionId//$("#ssid").val()
						},
						port : 'C_H5_3020', //抽奖
						success : function(data){
							let result = data ;
							// var result = JSON.stringify(data)
							console.log(result)
							if(result.drawUserRecord){
								if(result.drawUserRecord.couponType == "04"){
									// var locations = {"4":1,"2":3,"3":6,"-1":4};
									// var locations = {"5":2,"3":4,"-1":7};
									// -1代表随机黄金加息券
									var locations = {"5":1,"3":2,"-1":6};
									self.options.target = (function(num){ 
										num = parseInt(num);return locations[num] || locations['-1'];	
									})(result.drawUserRecord.couponValue);
								}else if(result.drawUserRecord.couponType == "01"){
                                    let stack = [0,3];
									self.options.target = stack.splice(parseInt(Math.random() * stack.length), 1)[0];
								}else{
									// 
									self.options.target = lotteryTool.getLocation(result.drawUserRecord.couponType);
								}
								if(result.drawUserRecord.couponType == "07"){
									// var stack = [2,5];
									let stack = [7];
									self.options.target = stack.splice(parseInt(Math.random() * stack.length), 1)[0];

									lotteryTool.isPrize = 0;
									
								}else{
									lotteryTool.isPrize = 1;
									
									$(".winnging").append(fill(result.drawUserRecord));
									lotteryTool.winning.append(fill(result.drawUserRecord,true));
								}
							}
							

						},
						error : function(e){
							self.options.target = 1;
							lotteryTool.isPrize = -1;
							//self.stop();
							alert("网络异常，请退出重新抽取");
						}
					});
				},
				stop: function () {	
								
					$(".mask").show();					
					if(lotteryTool.isPrize === 1){
							
						$(".td_5 a").click(function(){
							lotteryTool.turn("coupon");
						});
						$(".winnging").show();
						
					}else if(lotteryTool.isPrize === 0){
						
						$(".not-winning").show();
						
					}else if(lotteryTool.isPrize === -1){
						//window.location.reload() 
					}else{
						
					}
					// 刷新抽奖记录列表
				   adminLotteryRecords(promotNo)
				   allLotteryRecords(promotNo)
					
				}	
			});
		})
	}
    //用模板编译 
        const fill = function(data,flag){
			var html = '';
			if(data.couponType == "01"){ //展示 随机 加息券 仅此一种情况 没有定额的
				html = `<div class="winMask-cont giftMoney">
							<div class="winingInfo">
								<h2>${lotteryTool.parseNum(data.couponValue)}<span>${lotteryTool.getUnit(data.couponType)}</span></h2>
								<p class="prizeName">${lotteryTool.getPrizeName(data.couponType)}</p>
								<p class="p-btn-box"><a href="javascript:lotteryTool.turn(\'coupon\')" class="btn">立即查看>></a></p>
							</div>
						   <div class="winBg">
						   	<h3 class="winTit">棒棒哒，<br>明天还会有哦</h3>
								<img src="images/complianceOn-imgs/giftMoney_bg.png">
							</div>
					    </div>`;
			}else{  //展示随机（数字随机）红包，随机（数字）定额黄金加息券 
	              html = `<div class="winMask-cont goldLoans goldNum ">
							<div class="winingInfo">
								<h2>${lotteryTool.parseNum(data.couponValue)}<span>${lotteryTool.getUnit(data.couponType)}</span></h2>
								<p class="prizeName">${lotteryTool.getPrizeName(data.couponType)}</p>
								<p class="p-btn-box"><a href="javascript:lotteryTool.turn(\'coupon\')"  class="btn">立即查看>></a></p>
							</div>
						   <div class="winBg">
						  	<h3 class="winTit">棒棒哒，&nbsp;&nbsp;<br>明天还会有哦</h3>
								<img src="images/complianceOn-imgs/rateCoupon_bg.png">
							</div>
					    </div>`;
			}
			lotteryTool.edmond = lotteryTool.getEdmond(data.couponType);
			return html;
		};
       
       getPromotNo().then(function(promotNo){
			   //   alert('promotNo'+promotNo)
			   //   console.log(promotNo)
			// //获取活动编号之后发出下面请求
			//  promotNo = "P1807051805222001415"
			 //用户抽奖记录
			 if(promotNo == "该活动已经停止"){
			 	alert(promotNo)
                $(".spinner").hide();
			     lotteryTool.lottery.show();
			     return false ;
			 }
			 allLotteryRecords(promotNo).catch();
			 adminLotteryRecords(promotNo).catch(); 
			 
			 //查询能否抽奖 
			 hasRightDraw(promotNo).then((flag) => {
			 	// 你能抽奖返回成功状态
			 	// 执行抽奖方法
		        clickDraw(promotNo).catch()
			 },(err)=>{
			 	// 抛出一个reject 不去处理会报错
			 	
			 }).catch()
			
		},function(err){
			console.log(err);
			Login2()
	}).catch()	

});